import UIKit

public enum YHAppSettingURLType: String {
  case setting = "QXBwLXByZWZzOg=="
  case wifi = "QXBwLXByZWZzOldJRkk="
  case ble = "QXBwLXByZWZzOkJsdWV0b290aA=="
  case cellular = "QXBwLXByZWZzOk1PQklMRV9EQVRBX1NFVFRJTkdTX0lE"
  case apns = "QXBwLXByZWZzOk5PVElGSUNBVElPTlNfSUQ="
  case privacy = "QXBwLXByZWZzOlByaXZhY3k="
  case appSetting = "QXBwLXByZWZzJTNBY29tLmFycGhhLmFycGhhcGx1cw=="
}

public class YHAppSettingURLHelper {
  public static func gotoURL(_ urlType: YHAppSettingURLType) {
    let base64String = urlType.rawValue
    guard let data = Data(base64Encoded: base64String),
          let decodedString = String(data: data, encoding: .utf8),
          let url = URL(string: decodedString)
    else {
      // 如果解码失败，回退到应用设置页面
      fallbackToAppSettings()
      return
    }
//        var settingURL = URL(string: "prefs:root=WIFI")
    if UIApplication.shared.canOpenURL(url) {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
      fallbackToAppSettings(urlType: urlType)
    }
  }

  private static func fallbackToAppSettings(urlType: YHAppSettingURLType? = nil) {
    var fallbackURL = URL(string: UIApplication.openSettingsURLString)!
    if urlType == .apns, #available(iOS 16.0, *) {
      fallbackURL = URL(string: UIApplication.openNotificationSettingsURLString)!
    }
    UIApplication.shared.open(fallbackURL, options: [:], completionHandler: nil)
  }
}
